package tp1;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;

public class SynchroniserDossiers {
	
	public static int PLUS_RECENT = 1;
	public static int TAILLE_GRAND = 2;
	
private File dossier1;
private File dossier2;
private int param;

public SynchroniserDossiers(String dir1, String dir2 , int param) {
	setDossier1(new File(dir1));
	setDossier2(new File(dir2));
	this.param = param;
	
	if (getDossier1().isFile() || getDossier2().isFile()){
		System.out.println("ce ne sont pas des dossiers");
	}	
}
private void syncroniser() {
	ArrayList<File> listFiles1 =
		new ArrayList<File>(Arrays.asList(dossier1.listFiles()));
	
	ArrayList<File>  listFiles2 = 
		new ArrayList<File>(Arrays.asList(dossier2.listFiles()));
	
	synroniseFiles(listFiles2, listFiles1  , dossier2,dossier1);
	synroniseFiles(listFiles1,listFiles2 , dossier1, dossier2);
}




private void synroniseFiles(ArrayList<File> listFiles1,
		ArrayList<File> listFiles2, File dossier12, File dossier22) {
	for (File file : listFiles1) {
		if (indexof(listFiles2, file) > -1){
			// il existe
			File file2 = listFiles2.get(indexof(listFiles2, file));
			if (!isIdentique(file, file2)){
				if (getCritere(file,file2)){
					CopyFile.copyfile(file.getAbsolutePath(), dossier22.getAbsolutePath());
				} else  {
					CopyFile.copyfile(file2.getAbsolutePath(), dossier12.getAbsolutePath());
				}
			}				
		} else {		
			CopyFile.copyfile(file.getAbsolutePath(), dossier22.getAbsolutePath());
		}
	}
	
}

private int indexof (ArrayList<File> listFiles, File file) {
	int retour = -1;
	for (int i=0 ; i<listFiles.size() ;i++){
		File lFile = listFiles.get(i);
		if (lFile.getName().equals(file.getName())){
			retour= i;
			i=listFiles.size();
		}
	}
	return retour;
}

private boolean getCritere(File file, File file2) {
	boolean retour = false;
	if (param == TAILLE_GRAND) retour = file.getTotalSpace()> file2.getTotalSpace();
	if (param == PLUS_RECENT) retour = file.lastModified() > file2.lastModified();
	return retour;
}

private boolean isIdentique(File file, File file2) {
	boolean retour = false;
 retour = file.getTotalSpace() ==  file2.getTotalSpace();
	return retour;
}



public void setDossier1(File dossier1) {
	this.dossier1 = dossier1;
}
public void setDossier2(File dossier2) {
	this.dossier2 = dossier2;
}

public File getDossier2() {
	return dossier2;
}
public File getDossier1() {
	return dossier1;
}
public static void main(String[] args) {
	String dir1 = "testFolder/dir1/";
	String dir2 = "testFolder/dir2/";
	new SynchroniserDossiers(dir1, dir2, SynchroniserDossiers.TAILLE_GRAND).syncroniser();
}
}
